{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:07:33.603513Z",
     "start_time": "2025-05-15T12:07:33.588703Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "import pandas as pd\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.metrics import accuracy_score, precision_recall_fscore_support\n",
    "from sklearn.preprocessing import StandardScaler"
   ],
   "id": "c229b47cea6fb49a",
   "outputs": [],
   "execution_count": 121
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:07:33.664854Z",
     "start_time": "2025-05-15T12:07:33.650279Z"
    }
   },
   "cell_type": "code",
   "source": [
    "features = [\n",
    "    'Pregnancies',          # 怀孕次数\n",
    "    'Glucose',              # 葡萄糖浓度\n",
    "    'BloodPressure',        # 血压值（舒张压）\n",
    "    'SkinThickness',        # 皮肤褶皱厚度\n",
    "    'Insulin',              # 胰岛素水平\n",
    "    'BMI',                  # 身体质量指数\n",
    "    'DiabetesPedigreeFunction',  # 糖尿病遗传谱系功能值\n",
    "    'Age'                   # 年龄\n",
    "]\n",
    "\n",
    "# 目标变量（标签）\n",
    "target = ['Outcome']         # 是否患有糖尿病（1=是，0=否）\n",
    "dc_listings = pd.read_csv('../CSV/test.csv')\n",
    "x = dc_listings[features]\n",
    "y = dc_listings[target]\n",
    "X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.2, random_state=42)"
   ],
   "id": "34ba90da30c802af",
   "outputs": [],
   "execution_count": 122
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:07:33.711208Z",
     "start_time": "2025-05-15T12:07:33.697629Z"
    }
   },
   "cell_type": "code",
   "source": [
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)"
   ],
   "id": "58813324b0a6e42c",
   "outputs": [],
   "execution_count": 123
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:51:06.340369Z",
     "start_time": "2025-05-15T12:07:33.759819Z"
    }
   },
   "cell_type": "code",
   "source": [
    "model = KNeighborsClassifier(n_neighbors=5,weights='distance', algorithm='brute', metric='euclidean')\n",
    "model.fit(X_train_scaled, Y_train)\n",
    "y_preb = model.predict_proba(X_test_scaled)\n",
    "print(y_preb[:5])\n",
    "# 7. 提取正类概率（第二列）\n",
    "positive_probs = y_preb[:, 0]  # 提取所有样本的正类概率\n",
    "\n",
    "# 8. 手动转换：概率>0.5的标记为1，否则为0\n",
    "y_pred = (positive_probs > 0.5).astype(int)  # 将布尔值转为整数0/1\n"
   ],
   "id": "5493ad58f5779fc8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.80870484 0.19129516]\n",
      " [0.74115175 0.25884825]\n",
      " [1.         0.        ]\n",
      " [0.50079936 0.49920064]\n",
      " [0.1716953  0.8283047 ]]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "p:\\Python_DataAnalyze\\venv\\lib\\site-packages\\sklearn\\neighbors\\_classification.py:239: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().\n",
      "  return self._fit(X, y)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.80870484 0.19129516]\n",
      " [0.74115175 0.25884825]\n",
      " [1.         0.        ]\n",
      " [0.50079936 0.49920064]\n",
      " [0.1716953  0.8283047 ]]\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:51:06.409634Z",
     "start_time": "2025-05-15T12:51:06.402918Z"
    }
   },
   "cell_type": "code",
   "source": [
    "accuracy = accuracy_score(Y_test, y_pred)\n",
    "print(accuracy)"
   ],
   "id": "b3cc2eaa0ba05c71",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.3181818181818182\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:51:06.558694Z",
     "start_time": "2025-05-15T12:51:06.550789Z"
    }
   },
   "cell_type": "code",
   "source": [
    "precision, recall, fl_score , _ = precision_recall_fscore_support(Y_test, y_pred,average='binary')\n",
    "print(precision)\n",
    "print(recall)\n",
    "print(fl_score)"
   ],
   "id": "5e2c2c33a8c2dc55",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.26851851851851855\n",
      "0.5272727272727272\n",
      "0.3558282208588957\n"
     ]
    }
   ],
   "execution_count": 6
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
